package com.essc.controller;

import com.essc.pojo.User;
import com.essc.service.UserService;
import com.essc.utils.JwtUtil;
import com.essc.utils.LoginResult;
import com.essc.utils.SMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@CrossOrigin
@RestController
public class LoginController {
    @Autowired
    UserService userService;

    private static String code1;//全局变量
    //点击发送验证码 洪志成加
    @GetMapping("/sendMs/{tel}")
    public String sendMs (HttpServletRequest request,@PathVariable("tel") String tel){
        if(tel!=null&&!tel.equals("")){
            String s = SMSUtil.sendSMS(request,tel);
            return s;
        }else{
            return "error";
        }
    }

    //注册 洪志成改
    /*需要传入username password tel code*/
    @PostMapping("/register")
    public LoginResult register(@RequestBody User user,HttpServletRequest request) throws JSONException {
        System.out.println("接收到了注册请求"+user);
        Object count = userService.register(user.getUsername(), user.getPassword(),user.getTel(),user.getCode(),request);
        System.out.println(count);
        if (count.equals("error1")) {
            return LoginResult.fail("注册失败，用户名已存在");
        }else if (count.equals("error2")) {
            return LoginResult.fail("注册失败，该手机号已被注册");
        }else if(count.equals("success")){
            return LoginResult.success();
        }
        return LoginResult.fail(String.valueOf(count));
    }

    @GetMapping("/checkToken")
    public Boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return JwtUtil.checkToken(token);
    }

    //登录
    @PostMapping("/login")
    public LoginResult login(@RequestBody User user) {
        User result_user = userService.login(user.getUsername(), user.getPassword());
        if (!user.getVerifyCode().toUpperCase().equals(code1.toUpperCase())) {
            return LoginResult.fail("验证码错误");
        } else if (result_user == null) {
            return LoginResult.fail("登录失败，用户名或密码错误");
        } else {
            return LoginResult.success(result_user, JwtUtil.createToken());
        }
    }

    //得到验证码图片
    @GetMapping("/verifyCode")
    public String verifyCode(HttpServletResponse resp) throws IOException {
        code1 = userService.verifyCode(resp);
        return code1;
    }

}
